package Monitors.ReentrantLock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

import static ProcessThread.util.Sleeper.sleep;

@Slf4j(topic = "c.可打断")
public class 可打断 {

    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        Thread t1 = new Thread(() -> {
            log.debug("启动...");
            try {
                //如果没有竟争那么此方法就会获取Lock对象锁
                //如果有竞争就进入阻塞队列，可以被其它线程用interruput方法打断
                lock.lockInterruptibly();

                log.debug("获得了锁");
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.debug("等锁的过程中被打断");
                return;
            }
            finally {
                lock.unlock();
            }
        }, "t1");
        lock.lock();//主线程竞争
        log.debug("主线程获得了锁");
        t1.start();
        try {
            sleep(1);
            t1.interrupt();//wait 变成running
            log.debug("执行打断");
        } finally {
            lock.unlock();
        }
    }
}
